<template>
  <div class="color-picker">
    <i-input type="text" v-model="innerValue" @on-change="onInputChanged">
      <picker
        slot="append"
        v-model="pickerValue"
        :editable="false"
        class="picker-handler"
        @on-change="onPickerChanged"
      />
    </i-input>
  </div>
</template>

<script lang="ts">
import { Component, Model, Watch, Vue } from 'vue-property-decorator';
import { ColorPicker as Picker } from 'view-design';

@Component({
  components: {
    Picker,
  },
})
export default class ColorPicker extends Vue {
  protected innerValue = '';
  protected pickerValue = '';

  @Model('input')
  protected value!: string;

  @Watch('value', { immediate: true })
  protected onValueChanged(newVal: string, oldVal: string) {
    if (newVal == oldVal) return;

    this.innerValue = this.value;
    this.pickerValue = this.value;
  }

  protected onInputChanged() {
    if (/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(this.innerValue)) {
      this.pickerValue = this.innerValue;
      this.emitEvent();
    }
  }

  protected onPickerChanged() {
    this.innerValue = this.pickerValue;
    this.emitEvent();
  }

  protected emitEvent() {
    this.$emit('input', this.innerValue);
    this.$emit('on-chnage', this.innerValue);
  }
}
</script>

<style lang="scss" scoped>
.color-picker {
  position: relative;

  .picker-handler {
    margin-top: -1px;
    cursor: pointer;

    ::v-deep {
      .ivu-color-picker-input {
        border-width: 0;
        background-color: transparent;
        height: auto !important;
        padding: 0 !important;
        line-height: 1 !important;
      }
    }
  }
}
</style>
